<template>
  <van-nav-bar
    title="登录"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
  />
  <div class="login-wrap">
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="uname"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="upwd"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button round block color="#e50055" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
  <div class="bottom">
    <van-checkbox v-model="checked" shape="square" checked-color="#ee0a24"
      >记住密码</van-checkbox
    >
    <div class="register" @click="toRegister">点击注册</div>
  </div>
</template>

<script>
import { reactive, toRefs } from "@vue/reactivity";
import axios from "../utils/axios";
import { Toast } from "vant";
import { setLocal } from "../utils/utils";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
export default {
  setup() {
    const store = useStore();
    const router = useRouter();
    const state = reactive({
      username: "",
      password: "",
      checked: false,
    });
    // navbar 返回按钮
    const onClickLeft = () => history.back();
    //登录按钮
    const onSubmit = (values) => {
      // console.log("submit", values);
      axios.post("/login", values).then((res) => {
        // console.log(res);
        if (res.data.code == 8001) {
          Toast.fail(res.data.message);
        } else if (res.data.code == 200) {
          Toast.success(res.data.message);
          setLocal("token", res.data.token);
          setLocal("userinfo", JSON.stringify(res.data.result));
          store.commit("loginStatus");
          router.push({ path: "/mine" });
        }
      });
    };
    const toRegister = () => {
      router.push("/register");
    };
    return {
      ...toRefs(state),
      onClickLeft,
      onSubmit,
      toRegister,
    };
  },
};
</script>

<style lang = "less" scoped>
.bottom {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  font-size: 14px;
  .register {
    color: rgb(47, 0, 255);
    margin-right: 10px;
  }
}
</style>